package com.ymttest.database.mongo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.database.MongoDBDriver;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

import oracle.net.aso.r;

public class UserTokenWapper {
	MongoDBDriver mdd;

	public UserTokenWapper() throws Exception {
		mdd = new MongoDBDriver(EnvSetup.getSystemUrl("set5_mongoip"),27017, "Ymt_Auth_Token");
		mdd.setPoolSize(Integer.valueOf(EnvSetup.getSystemUrl("mongoPoolSize")));
		mdd.auth("authuser", "123456");
		mdd.selectCollection("UserToken");
	}

	/**
	 * 改变表
	 * 
	 * @param Collection
	 *            表名
	 */
	public void changeCollection(String Collection) {
		mdd.selectCollection(Collection);
	}
	
	/**
	 * 根据用户Id查询userToken
	 * @param uid
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getUserTokenByUid(int uid) throws Exception {
		Map<String, Object> scmb = new HashMap<String, Object>();
		ArrayList<Map> list = mdd.selectPartLimitToMap("{\"uId\":" + uid + "}",
				"{'_id':1, 'tId':1, 'sId':1, 'uId':1, 'eTtime':1, 'cTime':1, 'tSource':1,'deviceId':1}", 1, "{'cTime':-1}");
		try {
			if (list.size() > 0) {
				scmb = list.get(0);
				return scmb;
			}
		} catch (Exception e) {
			Logger.debug("err data uid:" + uid);
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * 用uid查询AccessToken
	 * 
	 * @param uid
	 * @return AccessToken
	 * @throws Exception
	 */
	public String getAccessTokenByUid(int uid) throws Exception {
		String re = null;
		UserTokenMatouAppBean scmb = null;
		ArrayList<String> list = mdd.selectPartLimit("{\"uId\":" + uid + "}", 1);
		try {
			if (list.size() > 0) {
				re = list.get(0);
				scmb = (UserTokenMatouAppBean) FormatUtil.GSONToObject(re, UserTokenMatouAppBean.class);
				return scmb.getsId();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从tSource为传入参数的100个记录中随机获取一个记录
	 * @param tSource
	 * @return { "_id" : "000105e2b46e4e4aafd9bac2f8f26a31" , "tId" : "564e6236b99c4dd6aa62c09316ebe4dd" , "sId" : "47D78662C0BC016B62D926D9374CDB55B39E6072ED9C9873371D57D5545012571C7B170DFCC9B029F9C99F147141F74AE0CC4C2BBA7A36F7" , "uId" : 1753206 , "eTtime" : { "$date" : "2015-03-10T01:54:56.181Z"} , "cTime" : { "$date" : "2015-03-03T01:54:56.181Z"} , "tSource" : "app" , "tContext" : "reg"}
	 * @throws Exception
	 */
	public String getUserTokenBytSource(String tSource) throws Exception {
		String scmb =null;
		ArrayList<String> list = mdd.selectPartLimit("{\"tSource\":\"" + tSource + "\"}", 100);
		try {
			if (list.size() >0) {
				scmb = list.get(new Random().nextInt(list.size()));
				return scmb;
			}
		} catch (Exception e) {
			Logger.debug("err data tSource:" + tSource);
			e.printStackTrace();
		}
		return null;
	}
	
	public List<Map> getUserTokenByUserId(Integer userId) throws Exception{
		BasicDBObject search = new BasicDBObject();
		search.append("uId", userId);
//		search.append("isnew", true);
//		.field("newstart").lessThanOrEq(now)
//	    .field("newend").greaterThanOrEq(now)
//		Date d1 = YMTDateUtil.getDate(getnewestproductlistbyselleridanddateBean.getDate(),"yyyy-MM-dd");
//		Date d2=YMTDateUtil.getBeforeOrNextDate(d1, 1);
		
		
//		search.append("newstart", new BasicDBObject("$lte", new Date()));
//		search.append("newend", new BasicDBObject("$gte", YMTDateUtil.getBeforeOrNextDate(new Date(), -7)));
		
//		BasicDBObject search1=new BasicDBObject("newstart", new BasicDBObject("$lte",d2));
//		BasicDBObject search2=new BasicDBObject("newstart", new BasicDBObject("$gte", d1));
//		BasicDBObject andObj = new BasicDBObject("$and",Arrays.asList(search));
//		BasicDBObject orderBy = new BasicDBObject("newstart", -1);
		Logger.debug("search:"+search.toString());
		List<Map> dlist = new UserTokenWapper().selectTokenInfo(search);
		return dlist;
	}
	
	
	
	
	public List<Map> selectTokenInfo(BasicDBObject search) throws Exception{
		List<Map> list=new ArrayList<>();
		BasicDBObject queryObject = new BasicDBObject(search);
		DBCursor db = mdd.getCollection().find(queryObject);
		/*if(orderBy!=null){
			db.sort(orderBy);
		}*/
			db.forEach(action->{
				list.add(action.toMap());
		});
		
		return list;
	}

	
	
	public List<String> getUserTokenBytSources(String tSource,int limit) throws Exception {
		String scmb =null;
		ArrayList<String> list = mdd.selectPartLimit("{\"tSource\":\"" + tSource + "\"}", limit);
		try {
			if (list.size() >0) {
				return list;
			}
		} catch (Exception e) {
			Logger.debug("err data tSource:" + tSource);
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * @param findJson
	 * @return
	 * @throws Exception
	 */
	public WriteResult deleteData(String findJson) throws Exception {
		return mdd.delete(findJson);
	}
	
	
	/**
	 * 根据用户token查询userid
	 * @param sid
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getUserUidByToken(String sId) throws Exception {
		Map<String, Object> scmb = new HashMap<String, Object>();
		ArrayList<Map> list = mdd.selectPartLimitToMap("{\"sId\":'" + sId + "'}",
				"{'_id':1, 'tId':1, 'sId':1, 'uId':1, 'eTime':1,'uTime':1, 'cTime':1, 'tSource':1}", 1, "{'cTime':-1}");
		try {
			if (list.size() > 0) {
				scmb = list.get(0);
				return scmb;
			}
		} catch (Exception e) {
			Logger.debug("err data uid:" + sId);
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 更新开始时间
	 * @param userId
	 * @param ctime
	 * @throws Exception
	 */
	public void updateStartTimeByUserId(Integer userId,Date ctime) throws Exception{
		BasicDBObject queryObject=new BasicDBObject("uId", userId);
		BasicDBObject updateObject = new BasicDBObject("$set",  new BasicDBObject("cTime", ctime));
		WriteResult w = mdd.update(queryObject,updateObject,false,false);
		if(w.getN()==0){
			Thread.sleep(5000);
			w = mdd.update(queryObject,updateObject,false,false);
		}
	}
	/**
	 * 更新结束时间
	 * @param userId
	 * @param ctime
	 * @throws Exception
	 */
	public void updateEndTimeByUserId(Integer userId,Date etime) throws Exception{
		BasicDBObject queryObject=new BasicDBObject("uId", userId);
		BasicDBObject updateObject = new BasicDBObject("$set",  new BasicDBObject("eTime", etime));
		WriteResult w = mdd.update(queryObject,updateObject,false,false);
		if(w.getN()==0){
			Thread.sleep(5000);
			w = mdd.update(queryObject,updateObject,false,false);
		}
	}
	/**
	 * 修改更新时间
	 * @param userId
	 * @param etime
	 * @throws Exception
	 */
	public void updateUTimeByUserId(Integer userId,Date utime) throws Exception{
		BasicDBObject queryObject=new BasicDBObject("uId", userId);
		BasicDBObject updateObject = new BasicDBObject("$set",  new BasicDBObject("uTime", utime));
		WriteResult w = mdd.update(queryObject,updateObject,false,false);
		if(w.getN()==0){
			Thread.sleep(5000);
			w = mdd.update(queryObject,updateObject,false,false);
		}
	}
}
